using System;
using System.Collections.Generic;

namespace TangCaptureTraffic.Services
{
    /// <summary>
    /// 数据格式化服务实现类，提供数据格式化和显示相关的实用方法
    /// </summary>
    public class DataFormattingService : IDataFormattingService
    {
        private static readonly Dictionary<string, string> ContentTypeMap = new Dictionary<string, string>
        {
            { "application/json", "JSON" },
            { "application/xml", "XML" },
            { "text/html", "HTML" },
            { "text/css", "CSS" },
            { "text/javascript", "JS" },
            { "application/javascript", "JS" },
            { "image/png", "PNG" },
            { "image/jpeg", "JPEG" },
            { "image/gif", "GIF" },
            { "image/svg+xml", "SVG" },
            { "application/pdf", "PDF" },
            { "text/plain", "Text" }
        };

        private static readonly string[] FileSizeUnits = { "B", "KB", "MB", "GB", "TB" };

        /// <summary>
        /// 格式化文件大小，将字节数转换为可读的格式（B、KB、MB、GB）
        /// </summary>
        /// <param name="bytes">字节数</param>
        /// <returns>格式化后的文件大小字符串</returns>
        public string FormatFileSize(long bytes)
        {
            if (bytes == 0) return "0 B";

            int order = 0;
            double size = bytes;

            while (size >= 1024 && order < FileSizeUnits.Length - 1)
            {
                order++;
                size = size / 1024;
            }

            return $"{size:0.##} {FileSizeUnits[order]}";
        }

        /// <summary>
        /// 格式化响应时间，根据时间长短选择合适的单位
        /// </summary>
        /// <param name="milliseconds">毫秒数</param>
        /// <returns>格式化后的时间字符串</returns>
        public string FormatResponseTime(int milliseconds)
        {
            if (milliseconds < 1000)
            {
                return $"{milliseconds} ms";
            }
            else if (milliseconds < 60000)
            {
                return $"{milliseconds / 1000.0:0.##} s";
            }
            else
            {
                int minutes = milliseconds / 60000;
                int seconds = (milliseconds % 60000) / 1000;
                return $"{minutes}m {seconds}s";
            }
        }

        /// <summary>
        /// 格式化HTTP状态码，为不同类型的状态码添加颜色标识
        /// </summary>
        /// <param name="statusCode">HTTP状态码</param>
        /// <returns>格式化后的状态码字符串</returns>
        public string FormatStatusCode(int statusCode)
        {
            if (statusCode == 0) return "--";

            string prefix = GetStatusCodePrefix(statusCode);
            return $"{prefix}{statusCode}";
        }

        /// <summary>
        /// 获取状态码前缀
        /// </summary>
        /// <param name="statusCode">HTTP状态码</param>
        /// <returns>状态码前缀</returns>
        private static string GetStatusCodePrefix(int statusCode)
        {
            return statusCode switch
            {
                >= 200 and < 300 => "✓ ", // 成功
                >= 300 and < 400 => "↗ ", // 重定向
                >= 400 and < 500 => "⚠ ", // 客户端错误
                >= 500 => "✗ ", // 服务器错误
                _ => ""
            };
        }

        /// <summary>
        /// 简化内容类型显示，只显示主要类型
        /// </summary>
        /// <param name="contentType">完整的Content-Type头</param>
        /// <returns>简化后的内容类型</returns>
        public string SimplifyContentType(string contentType)
        {
            if (string.IsNullOrEmpty(contentType)) return "--";

            // 只取分号前的部分
            var mainType = contentType.Split(';')[0].Trim();

            return ContentTypeMap.TryGetValue(mainType, out var simplifiedType) ? simplifiedType : mainType;
        }

        /// <summary>
        /// 格式化请求时间为简短格式
        /// </summary>
        /// <param name="dateTime">请求时间</param>
        /// <returns>格式化后的时间字符串</returns>
        public string FormatRequestTime(DateTime dateTime)
        {
            return dateTime.ToString("HH:mm:ss.fff");
        }
    }
}